package cn.matezk.lianlian.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.ObjectUtil;
import cn.matezk.lianlian.dao.UserDao;
import cn.matezk.lianlian.model.User;
import cn.matezk.lianlian.service.IWechatService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WechatService implements IWechatService {
    @Value("${miniapp.env}")
    private String env;

    @Autowired
    private UserDao userDao;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMaService wxMaService;

    @Override
    public void syncUsers() throws WxErrorException {
        String nextOpenId = "";
        while (true) {
            WxMpUserList list = wxMpService.getUserService().userList(nextOpenId);
            for (String openid : list.getOpenids()) {
                subscribe(openid);
            }
            if (list.getCount() != 10000)   break;
            nextOpenId = list.getNextOpenid();
        }
    }

    @Override
    public void subscribe(String openid) throws WxErrorException {
        WxMpUser wu = wxMpService.getUserService().userInfo(openid, "zh_CN");
        if (ObjectUtil.isEmpty(wu.getUnionId()))
            return;
        User user = userDao.selectByPrimaryKey(wu.getUnionId());
        if (ObjectUtil.isNull(user)) {
            user = new User();
            user.setUnionId(wu.getUnionId());
            user.setOpenId(wu.getOpenId());
            user.setIsSub(Boolean.TRUE);
            userDao.insertSelective(user);
        } else {
            user.setOpenId(openid);
            user.setIsSub(Boolean.TRUE);
            userDao.updateByPrimaryKeySelective(user);
        }
    }

    @Override
    public void unsubscribe(String openid) throws WxErrorException {
        User user = new User();
        user.setOpenId(openid);
        user.setIsSub(Boolean.FALSE);
        user.setWechatNotifyEnable(Boolean.FALSE);
        userDao.updateByOpenIdSelective(user);
    }
}
